﻿using ClassLib;
using FanjiaHotelPlatform.utils.Kits;
using log4net.Repository.Hierarchy;
using Maticsoft.DBUtility;
using MySql.Data.MySqlClient;
using Newtonsoft.Json;
using Org.BouncyCastle.Crypto.Tls;
using Polly;
using Polly.Caching;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection.Emit;
using System.Runtime.Remoting.Messaging;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using System.Web.Caching;
using System.Web.Script.Serialization;
using System.Windows.Forms;
using System.Xml;
using WindowsFormsApplication1.Common;
using Z.BulkOperations;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.ProgressBar;

namespace WindowsFormsApplication1
{
    public partial class DataTran : Form
    {
        private DataTable dtBrand;

        public DataTran()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //var ssss = AES.Decode("8xbyMxHVLq/J/UnSv4Z7PaEQtzjZKmjyiv2pJpRAFfZKYtTE1vmtK3aJoB1Gc30CzVgJORfQnPwTmj59J2FPpe7j79imHQnEcix6q8eNjBOKilbg4O2E8hjmT99GYQBavoxtb88a2WeP8Ydegr8/FVfmGDXK1MFtXCz8D7fpkYs=", "Fanjia@HotelManager.2017");
            //MessageBox.Show(ssss);
            //return;
            //HotelMergeAllCity();
            //return;

            //var list = new List<Form6.HotelRoomStatusReq>();
            //var item = new Form6.HotelRoomStatusReq
            //{
            //    Days = 1,
            //    EndOfDay = "11",
            //    InnId = "aaa"
            //};

            //for (int i = 0; i < 5; i++)
            //{
            //    list.Add(item);
            //}
            //return;

            //DistrictCodeRefresh();
            //DistrictDataRefresh();
            //DistrictDataDeal();

            LowPriceDataClear();
            MessageBox.Show("OK!");

            return;
            PollyTest();
            var t = DateTime.Parse("23:59:59.999");
            //var r = IsInVoiceNotifyTime();
            //CTripRequestTest();

            MessageBox.Show("OK!");

            return;

            var ss =
                "http://dimg04.c-ctrip.com/images/200r0e000000733j5E0C2_R_550_412.jpg                                                                                                                                                                                      ";

            ss = ss.TrimEnd();
            MessageBox.Show(ss);

            //CreateMinPriceIndex();

            //CreateQTPicTable();
            return;

            List<string> test = new List<string>();

            var a = test.FirstOrDefault(s => s == "1");

            if (a == null)
                MessageBox.Show("ddd");

            return;

            TestMain();
            //string a = "http://www.baidu.com";
            MessageBox.Show("OK");

            //CollectTest();

            //CreateImgTableIndex();
            //SetHotelLogoImage();
            //CreateFunction();
            //TranData();

            //GetTuniuInfoByWebBrowser();
            //GetTuniuInfo();

            //TranDataTo();

            //Dictionary<string, string> cacheDic = new Dictionary<string, string>();
            //cacheDic.Add("1","aaa");
            //cacheDic.Add("2","bbb");

            //Dictionary<string, string> cacheDic = HttpRuntime.Cache["RndBookingInfo"] as Dictionary<string, string>;
            //if (cacheDic == null)
            //{
            //    cacheDic = new Dictionary<string, string>();
            //}

            //cacheDic.Add("ddd","1111");
            //HttpRuntime.Cache.Insert("RndBookingInfo", cacheDic, null, DateTime.Today.AddDays(1), Cache.NoSlidingExpiration);

            //Random rd = new Random();
            //int mm = rd.Next(-1, 2);


            //double a = Math.Ceiling(5.21);
            //int b = (int)a;

            //string m = "0:00";
            //DateTime dt = DateTime.Parse(m);

            //MessageBox.Show(DateTime.Today.AddDays(1).ToString());
        }

        /// <summary>
        /// 是否在自动呼叫设置时间范围内
        /// </summary>
        /// <param name="voiceNotifyConfig">自动呼叫配置信息实体</param>
        /// <returns></returns>
        public bool IsInVoiceNotifyTime()
        {
            if (true)
            {
                DateTime callStart;
                bool sFlag = DateTime.TryParse("23:00", out callStart);
                DateTime callEnd;
                bool eFlag = DateTime.TryParse("00:00", out callEnd);
                if (sFlag && eFlag)
                {
                    DateTime dtNow = DateTime.Parse("06:00");
                    if (DateTime.Compare(callStart, callEnd) > 0) //判断是否跨天情况
                    {
                        if (DateTime.Compare(dtNow, callEnd) < 0) //根据当前时间推断自动呼叫时间范围
                            callStart = callStart.AddDays(-1);
                        else
                            callEnd = callEnd.AddDays(1);
                    }
                    //判断是否在呼叫时间范围
                    if (DateTime.Compare(dtNow, callStart) >= 0 && DateTime.Compare(dtNow, callEnd) <= 0)
                    {
                        return true;
                    }
                }
            }
            return false;
        }

        private string JsonParse(string jsonData, string hotelCode)
        {
            //string jsonData =
            //    @"{'1':{'id':'1','name':'宾馆服务项目：','count':2,'rows':[{'9':'免费停车场'},{'12':'有无线上网的公共区域'}]},'2':{'id':'2','name':'宾馆餐饮设施：','count':1,'rows':[{'245':'酒店餐厅'}]},'3':{'id':'3','name':'宾馆娱乐与健身设施：','count':0,'rows':[]},'4':{'id':'4','name':'宾馆房间设施：','count':3,'rows':[{'58':'国内长途电话'},{'60':'免费一次性洗漱用品'},{'75':'24小时热水'}]},'5':{'id':'5','name':'宾馆会议设施：','count':1,'rows':[{'244':'商务中心'}]},'6':{'id':'6','name':'宾馆附加设施：','count':1,'rows':[{'242':'免费wifi'}]}}";

            JavaScriptSerializer jss = new JavaScriptSerializer();

            jsonData = jsonData.Replace("\\", "").Replace("\"", "'");

            ArrayList arrl = jss.Deserialize<ArrayList>(jsonData);

            try
            {
                //将指定的 JSON 字符串转换为 Dictionary<string, object> 类型的对象
                var rest = jss.Deserialize<Dictionary<string, object>>(jsonData);

                StringBuilder sb = new StringBuilder();

                foreach (var dis in rest)
                {
                    Dictionary<string, object> vList = (Dictionary<string, object>)dis.Value;

                    int count = 0;
                    StringBuilder subItem = new StringBuilder();

                    foreach (var v in vList)
                    {
                        if (v.Key == "name")
                        {
                            if (v.Value.ToString().Replace(":", "").Contains("："))
                            {
                                subItem.AppendFormat("{0}", v.Value);
                            }
                            else
                            {
                                subItem.AppendFormat("{0}：", v.Value);
                            }

                        }
                        if (v.Key == "rows")
                        {
                            var aList = v.Value as ArrayList;

                            foreach (Dictionary<string, object> item in aList)
                            {
                                foreach (var i in item)
                                {
                                    subItem.AppendFormat("{0}、", i.Value);
                                    count++;
                                }
                            }
                        }
                    }

                    if (count > 0)
                        sb.AppendFormat("{0}；", subItem.ToString().TrimEnd('、'));
                }

                return sb.ToString();

            }
            catch (Exception ex)
            {
                Tools.WriteInfoToFileNoRw(hotelCode + "【jsonData】" + jsonData + " |" + ex.Message);
                //throw new Exception(ex.Message);

                return string.Empty;
            }
        }

        private void TranData()
        {
            try
            {
                dtBrand = DbHelperSQL.Query("SELECT * FROM brand WHERE brand_code_fj IS NOT NULL").Tables[0];
                DataTable dt = DbHelperSQL.Query("SELECT FanjiaCityId,FanjiaCityCode,TuniuCityName FROM TuniuCityMapping WHERE TuniuCityName IS NOT NULL AND ISNULL(tranflag,0)<1 ORDER BY FanjiaCityCode").Tables[0];

                if (dt != null && dt.Rows.Count > 0)
                {
                    foreach (DataRow dr in dt.Rows)
                    {
                        if (string.IsNullOrEmpty(Convert.ToString(dr["TuniuCityName"])))
                            continue;

                        DataTable dtHotel = DbHelperSQL.Query($"SELECT * FROM hotel WHERE city_name LIKE '{dr["TuniuCityName"]}%'").Tables[0];

                        if (dtHotel.Rows.Count > 0)
                        {
                            DataTable dtNew = DbHelperSQL.Query("SELECT * FROM TuniuHotelDetail WHERE 1=0").Tables[0];
                            foreach (DataRow drHotel in dtHotel.Rows)
                            {
                                DataRow drNew = dtNew.NewRow();
                                drNew["hotel_code"] = drHotel["hotel_code"];
                                drNew["chinese_name"] = drHotel["chinese_name"];
                                drNew["english_name"] = drHotel["english_name"];
                                drNew["star"] = drHotel["star"];

                                drNew["star_fj"] = GetHotelStar(drHotel["star"].ToString());

                                drNew["hotel_type"] = drHotel["hotel_type"];
                                drNew["continent_code"] = drHotel["continent_code"];
                                drNew["country_code"] = drHotel["country_code"];
                                drNew["province_code"] = drHotel["province_code"];
                                drNew["city_code"] = drHotel["city_code"];
                                drNew["city_code_fj"] = dr["FanjiaCityCode"];

                                drNew["district_code"] = drHotel["district_code"];
                                drNew["country_name"] = drHotel["country_name"];
                                drNew["province_name"] = drHotel["province_name"];
                                drNew["city_name"] = drHotel["city_name"];
                                drNew["district_name"] = drHotel["district_name"];
                                drNew["address"] = drHotel["address"];
                                drNew["debut_year"] = drHotel["debut_year"];
                                drNew["decorate_date"] = drHotel["decorate_date"];
                                drNew["room_number"] = drHotel["room_number"];
                                drNew["latitude"] = drHotel["latitude"];
                                drNew["longitude"] = drHotel["longitude"];

                                drNew["facilites"] = JsonParse(Convert.ToString(drHotel["facilites"]),
                                    drHotel["hotel_code"].ToString());

                                drNew["tel"] = drHotel["tel"];
                                drNew["floors"] = drHotel["floors"];

                                drNew["feature"] = drHotel["feature"];

                                drNew["mobile"] = drHotel["mobile"];
                                drNew["email"] = drHotel["email"];
                                drNew["instruction"] = drHotel["instruction"];
                                drNew["detail"] = drHotel["detail"];
                                drNew["hotel_brand"] = drHotel["hotel_brand"];

                                drNew["brand_fj"] = GetFjBrand(drHotel["hotel_brand"].ToString());

                                //drNew["category"] = Convert.ToInt32(drHotel["category"]);
                                if (drHotel["fax"].ToString().Length < 100)
                                    drNew["fax"] = drHotel["fax"];
                                //drNew["NormalizedLongitude"] = drHotel["NormalizedLongitude"];
                                //drNew["NormalizedLatitude"] = drHotel["NormalizedLatitude"];
                                drNew["hotel_pic"] = string.Empty;
                                drNew["status"] = 1;

                                dtNew.Rows.Add(drNew);
                            }

                            DbHelperSQL.ExecuteSql(
                                $"DELETE FROM TuniuHotelDetail WHERE city_code_fj='{dr["FanjiaCityCode"]}'");

                            DbHelperSQL.SaveListDataBat(dtNew, "TuniuHotelDetail");

                            DbHelperSQL.ExecuteSql(
                                $"UPDATE TuniuCityMapping SET TranFlag=1 WHERE FanjiaCityCode='{dr["FanjiaCityCode"]}'");

                            DbHelperSQL.ExecuteSql(
                                $"INSERT INTO TuniuTranLog(SyncObject,SyncCount,SyncResult) VALUES('{dr["FanjiaCityCode"]}',{dtNew.Rows.Count},'数据转换完成')");
                        }

                    }
                }

                MessageBox.Show("转换完成！");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                Tools.WriteInfoToFileNoRw(ex.Message);
            }
        }

        private int GetHotelStar(string s)
        {
            int r = 0;
            switch (s)
            {
                case "1":
                    r = 5;
                    break;
                case "2":
                    r = 4;
                    break;
                case "3":
                    r = 3;
                    break;
                case "4":
                    r = 2;
                    break;
                case "5":
                    r = 5;
                    break;
                case "6":
                    r = 3;
                    break;
                case "7":
                    r = 2;
                    break;
                case "8":
                    r = 4;
                    break;
            }

            return r;
        }

        private string GetFjBrand(string b)
        {
            string r = string.Empty;
            DataRow[] drs = dtBrand.Select($"brand_code='{b}'");

            if (drs != null && drs.Length > 0)
            {
                return drs[0]["brand_code_fj"].ToString();
            }

            return r;
        }

        private void CreateFunction()
        {

            string sql = @"CREATE FUNCTION [dbo].[GetHotelImage_{0}]
            (
                @HotelCode NVARCHAR(50)
                )
            RETURNS VARCHAR(1000)
            AS
                BEGIN


            DECLARE @Url VARCHAR(1000)

            DECLARE @Sql NVARCHAR(500)


            SET @Url = (SELECT TOP 1 [url] FROM(
                    SELECT[hotel_code]
                    ,[city_code]
                ,[room_type_tn_id]
                ,[url], (CASE[category] WHEN '0' THEN 21 WHEN '' THEN 22  ELSE cast(category as int) END) categ
            FROM[TuniuHotelData].[dbo].[TuniuHotelImages_{0}]
            WHERE hotel_code = @HotelCode) a
                ORDER BY a.categ)


            RETURN @Url

            END";


            DataTable dt = DbHelperSQL.Query("SELECT ProvCode FROM TuniuDataGetProvList").Tables[0];

            if (dt != null && dt.Rows.Count > 0)
            {
                foreach (DataRow dr in dt.Rows)
                {
                    string exeSql = string.Format(sql, dr["ProvCode"].ToString());
                    int i = DbHelperSQL.ExecuteSql(exeSql);

                }
            }

            MessageBox.Show("ok");
        }

        private void CreateImgTableIndex()
        {
            string sql = @"IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id=OBJECT_ID('TuniuHotelImages_{0}', N'U') and NAME='index_hotel_code') BEGIN
   CREATE NONCLUSTERED INDEX [index_hotel_code] ON [dbo].[TuniuHotelImages_{0}]([hotel_code] ASC)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) END";
            string sql1 = @"IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id=OBJECT_ID('TuniuHotelImages_{0}', N'U') and NAME='index_room_type_tn_id') BEGIN
CREATE NONCLUSTERED INDEX [index_room_type_tn_id] ON [dbo].[TuniuHotelImages_{0}]([room_type_tn_id] ASC)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) END";

            DataTable dt = DbHelperSQL.Query("SELECT ProvCode FROM TuniuDataGetProvList").Tables[0];

            if (dt != null && dt.Rows.Count > 0)
            {
                foreach (DataRow dr in dt.Rows)
                {
                    string exeSql = string.Format(sql, dr["ProvCode"].ToString());
                    int i = DbHelperSQL.ExecuteSql(exeSql);

                    string exeSql1 = string.Format(sql1, dr["ProvCode"].ToString());
                    i = DbHelperSQL.ExecuteSql(exeSql1);

                }
            }

            MessageBox.Show("ok");
        }

        private void CreateMinPriceIndex()
        {
            string sql = @"IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id=OBJECT_ID('CozyHotelLowPrice_{0}', N'U') and NAME='Idx_HotelId') BEGIN
   CREATE NONCLUSTERED INDEX [Idx_HotelId] ON [dbo].[CozyHotelLowPrice_{0}]([HotelId] ASC)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) END";
//            string sql1 = @"IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id=OBJECT_ID('TuniuHotelImages_{0}', N'U') and NAME='index_room_type_tn_id') BEGIN
//CREATE NONCLUSTERED INDEX [index_room_type_tn_id] ON [dbo].[TuniuHotelImages_{0}]([room_type_tn_id] ASC)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) END";

            DataTable dt = DbHelperSQL.Query("SELECT ProvCode FROM CozyDataGetProvList").Tables[0];

            if (dt != null && dt.Rows.Count > 0)
            {
                foreach (DataRow dr in dt.Rows)
                {
                    string exeSql = string.Format(sql, dr["ProvCode"].ToString());
                    int i = DbHelperSQL.ExecuteSql(exeSql);

                    //string exeSql1 = string.Format(sql1, dr["ProvCode"].ToString());
                    //i = DbHelperSQL.ExecuteSql(exeSql1);

                }
            }

            MessageBox.Show("ok");
        }

        private void CreateQTPicTable()
        {
            var sqlCreate = @"CREATE TABLE [dbo].[QiantaoHotelPic_{0}](
	                    [Id] [uniqueidentifier] NOT NULL,
	                    [HotelCode] [nvarchar](200) NULL,
	                    [RoomCode] [nvarchar](200) NULL,
	                    [PicType] [nvarchar](50) NULL,
	                    [IsMain] [nvarchar](50) NULL,
	                    [IsRoomMain] [nvarchar](50) NULL,
	                    [PicUrl] [nvarchar](2000) NULL,
	                    [PS] [nvarchar](50) NULL,
	                    [CityCode] [nvarchar](50) NULL,
	                    [CreationTime] [datetime] NOT NULL,
                     CONSTRAINT [PK_dbo.QiantaoHotelPic_{0}] PRIMARY KEY CLUSTERED 
                    (
	                    [Id] ASC
                    )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
                    ) ON [PRIMARY]
                    ALTER TABLE [dbo].[QiantaoHotelPic_{0}] ADD  CONSTRAINT [DF_QiantaoHotelPic_{0}_Id]  DEFAULT (newsequentialid()) FOR [Id]
                    ALTER TABLE [dbo].[QiantaoHotelPic_{0}] ADD  CONSTRAINT [DF_QiantaoHotelPic_{0}_CreationTime]  DEFAULT (getdate()) FOR [CreationTime];
                    CREATE NONCLUSTERED INDEX [Idx_{0}_HotelCode] ON [dbo].[QiantaoHotelPic_{0}]
                    (
	                    [HotelCode] ASC
                    )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON)";

            DataTable dt = DbHelperSQL.Query("SELECT DISTINCT [FanjiaProvinceCode] FROM [QiantaoHotelData].[dbo].[QiantaoCityMapping] WHERE [QiantaoCityCode] IS NOT NULL").Tables[0];

            if (dt != null && dt.Rows.Count > 0)
            {
                foreach (DataRow dr in dt.Rows)
                {
                    //DbHelperSQL.ExecuteSql($"DROP TABLE QiantaoHotelPic_{dr["FanjiaProvinceCode"]}");

                    string exeSql = string.Format(sqlCreate, dr["FanjiaProvinceCode"].ToString());
                    int i = DbHelperSQL.ExecuteSql(exeSql);
                }
            }

            MessageBox.Show("ok");

        }

        private void SetHotelLogoImage()
        {
            try
            {
                DataTable dt = DbHelperSQL.Query("SELECT FanjiaCityId,FanjiaCityCode,TuniuCityName,FanjiaProvinceCode FROM TuniuCityMapping WHERE TuniuCityName IS NOT NULL ORDER BY FanjiaCityCode").Tables[0];

                if (dt != null && dt.Rows.Count > 0)
                {
                    foreach (DataRow dr in dt.Rows)
                    {
                        if (string.IsNullOrEmpty(Convert.ToString(dr["TuniuCityName"])))
                            continue;


                        DbHelperSQL.ExecuteSql(
                            $"UPDATE dbo.TuniuHotelDetail SET hotel_pic=dbo.GetHotelImage_{dr["FanjiaProvinceCode"]}(TuniuHotelDetail.hotel_code) WHERE city_code_fj='{dr["FanjiaCityCode"]}'");

                        DbHelperSQL.ExecuteSql(
                            $"INSERT INTO TuniuTranLog(SyncObject,SyncCount,SyncResult) VALUES('{dr["FanjiaCityCode"]}',0,'LOGO数据转换完成')");

                    }
                }

                MessageBox.Show("logo转换完成！");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                Tools.WriteInfoToFileNoRw(ex.Message);
            }
        }

        private void GetTuniuInfo()
        {
            try
            {
                DataTable dt = DbHelperSQL.Query("SELECT FanjiaCityId,FanjiaCityCode,TuniuCityName,FanjiaProvinceCode,TuniuCityCode FROM TuniuCityMapping WHERE TuniuCityName IS NOT NULL ORDER BY FanjiaCityCode").Tables[0];

                if (dt != null && dt.Rows.Count > 0)
                {
                    foreach (DataRow dr in dt.Rows)
                    {
                        if (string.IsNullOrEmpty(Convert.ToString(dr["TuniuCityName"])))
                            continue;

                        //string strUrl = $"http://hotel.tuniu.com/list?city={dr["TuniuCityCode"]}&checkindate=2018-2-3&checkoutdate=2018-2-4";

                        string strUrl = $"http://hotel.tuniu.com/list?city=1402&checkindate=2018-2-3&checkoutdate=2018-2-4";

                        var utils = new WebUtils();
                        string responseStr = utils.DoGet(strUrl, null, "UTF-8");

                        if (responseStr.Contains("学校") || responseStr.Contains("景点"))
                        {

                            DbHelperSQL.ExecuteSql(
                                $"INSERT INTO TuniuBaseInfo(FanjiaCityCode,TuniuCityCode,ReqContent) VALUES('{dr["FanjiaCityCode"]}','{dr["TuniuCityCode"]}','{responseStr}')");

                            Random r = new Random();
                            int m = r.Next(5, 10);
                            Thread.Sleep(m * 1000);
                        }
                        else
                        {
                            Tools.WriteInfoToFileNoRw(responseStr);
                            MessageBox.Show("被拦截！");
                            break;
                        }
                    }
                }

                MessageBox.Show("获取完成！");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                Tools.WriteInfoToFileNoRw(ex.Message);
            }
        }

        //private void GetTuniuInfoByWebBrowser()
        //{
        //    string urlStr = $"http://hotel.tuniu.com/list?city=1402&checkindate=2018-2-3&checkoutdate=2018-2-4";
        //    webKitBrowser1.Url = new Uri(urlStr);

        //    //Thread.Sleep(8000);

        //    //var htmlDoc = webKitBrowser1.Document;
        //}

        //private void webKitBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        //{
        //    if (webKitBrowser1.Url != null)
        //    {
        //        MessageBox.Show("加载完成");

        //        var htmlDoc = webKitBrowser1.Document;
        //    }
        //}

        private void TranDataTo()
        {
            try
            {
                DataTable dt = DbHelperSQL.Query("SELECT FanjiaCityId,FanjiaCityCode,TuniuCityName FROM TuniuCityMapping WHERE TuniuCityName IS NOT NULL ORDER BY FanjiaCityCode").Tables[0];

                if (dt != null && dt.Rows.Count > 0)
                {
                    foreach (DataRow dr in dt.Rows)
                    {
                        if (string.IsNullOrEmpty(Convert.ToString(dr["TuniuCityName"])))
                            continue;

                        DataTable dtHotel = DbHelperSQL.Query($"SELECT * FROM TuniuHotelDetail WHERE city_code_fj='{dr["FanjiaCityCode"]}'").Tables[0];

                        if (dtHotel.Rows.Count > 0)
                        {
                            DbHelperSQL.SaveListDataBatM(dtHotel, "TuniuHotelDetail", 2);

                            DbHelperSQL.ExecuteSql(
                                $"INSERT INTO TuniuTranLog(SyncObject,SyncCount,SyncResult) VALUES('{dr["FanjiaCityCode"]}',{dtHotel.Rows.Count},'数据转移完成')");
                        }

                    }
                }

                MessageBox.Show("数据转移完成！");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                Tools.WriteInfoToFileNoRw(ex.Message);
            }
        }

        private void CollectTest()
        {
            List<string> tList = new List<string>();

            Dictionary<string, string> dic = new Dictionary<string, string>();

            Stopwatch sw = new Stopwatch();
            sw.Start();

            Random rd = new Random();

            for (int i = 0; i < 1000000; i++)
            {
                //int m = rd.Next(0, 100000);

                string m = Guid.NewGuid().ToString();

                //if (!tList.Contains(m.ToString()))
                //    tList.Add($"{i + 1}");

                if (!dic.ContainsKey(m))
                    dic.Add(m, $"第{m + 1}个元素");
            }

            sw.Stop();

            MessageBox.Show(sw.ElapsedMilliseconds.ToString());
        }

        public async Task<string> TestMlt()
        {
            return await Task.Run(() =>
            {
                Thread.Sleep(2000);
                return DateTime.Now.ToString();
            });
        }

        public async Task TestMain()
        {
            List<Task<string>> tasks = new List<Task<string>>();

            for (int i = 0; i < 4; i++)
            {
                tasks.Add(TestMlt());
            }

            var rs = await Task.WhenAll(tasks);

            foreach (var r in rs)
            {
                Console.WriteLine(r);
            }
        }

        public void CTripRequestTest()
        {
            var dic = new Dictionary<string, string>();

            dic.Add("AID", "1");
            dic.Add("SID", "50");
            dic.Add("ICODE", "ccc56c891a4d4f4fa4fc78f0aec29d03");
            dic.Add("UUID", "f71dee19-9e09-42d9-a39c-40757d9d76e4");
            dic.Add("Token", "f8885e862f7840ebb91b5318d2e8a874");
            dic.Add("Mode", "1");

            string s = @"{
    'SearchTypeEntity': {
        'SearchType': 'WirelessSearch',
        'HotelCount': 3,
        'PageIndex': 1
    },
    'PublicSearchParameter': {
        'City': 2,
        'CheckInDate': '2019-01-25',
        'CheckOutDate': '2019-02-20',
        'HotelList': '',
        'FilterRoomByPerson': '2,999',
        'OnlyPPPrice': true,
        'OnlyFGPrice': false,
        'IsJustifyConfirm': 'T',
        'PlotType': 'StandardPlot'
    },
    'FacilityEntity': {
        'ChildrenAgeList': [
            8,
            9,
            10,
            11
        ]
    },
    'MapSearchEntity': {
        'DotX': 31.23482384,
        'DotY': 121.4610633,
        'Radius': 0.01
    },
    'OrderBy': {
        'OrderName': 'MinPrice',
        'OrderType': 'ASC'
    }
}";
            //dic.Add("Format", s);
            dic.Add("Format", "{\"City\": \"90\",\"PageIndex\": \"1\",\"PageSize\": \"6\"}");

            var appPath = "openservice.open.uat.ctripqa.com";
            var aId = "1";
            var sId = "50";
            var iCode = "50";
            var uuid = "50";
            var accessToken = "";

            WebUtils web = new WebUtils();
            accessToken = web.DoPost("http://192.168.1.228/api/Token/AccessToken");

            var reqUrl =
                $"http://{appPath}/openservice/serviceproxy.ashx?AID={aId}&SID={sId}&ICODE={iCode}&UUID={uuid}&Token={accessToken}&mode=1&format=JSON";

            
            var rst = web.DoPost("http://openservice.open.uat.ctripqa.com/openservice/serviceproxy.ashx", dic);
        }

        public string PollyGetApiTest(string m)
        {
            var jsonParams = @"{
                'CompanyId': '569fef3c-0020-4396-9be7-382b4c7d4eeb',
                'UserID': 'c81a2571-c04b-4604-af3f-dd435febd5af',
                'CityName': '杭州',
                'CheckInDate': '2019-03-15',
                'CheckOutDate': '2019-03-16',
                'PageNo': 1,
                'PageSize': 15
            }";
            var requestResult = WebRequestKit.CreateJsonPostHttpRequest("http://192.168.1.222:8181/AppHotel/GetHotelListNew", jsonParams, 10000, System.Text.Encoding.UTF8);
            return requestResult;
        }

        public void PollyTest()
        {
            //var policy = Policy.Handle<TimeoutException>()
            //    .WaitAndRetryAsync(3, retryAttempt => TimeSpan.FromSeconds(1), (exception, retryCount) =>
            //    {
            //        //logger.Error(exception);
            //        Console.WriteLine($"{retryCount}:{exception}");
            //    });
            var policy = Policy.Handle<Exception>()
                .WaitAndRetry(3, retryAttempt => TimeSpan.FromSeconds(1), (exception, retryAttempt, retryCount, context) =>
                {
                    //logger.Error(exception);
                    Console.WriteLine($"{retryCount}:{exception.Message}");
                });


            // 每次重试之间等待指定的时间间隔
            //var policySet = Policy
            //    .Handle<Exception>()
            //    .WaitAndRetry(new[]
            //    {
            //        TimeSpan.FromSeconds(1),
            //        TimeSpan.FromSeconds(1),
            //        TimeSpan.FromSeconds(1)
            //    });

            try
            {
                var rst = policy.Execute(() => PollyGetApiTest("1"));
                MessageBox.Show(rst);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                MessageBox.Show(e.Message);
            }
            
        }

        private void LowPriceDataClear()
        {
            try
            {
                DataTable dt = DbHelperSQL.Query("SELECT * FROM Provinces ORDER BY CODE").Tables[0];

                if (dt != null && dt.Rows.Count > 0)
                {
                    foreach (DataRow dr in dt.Rows)
                    {
                        LogHelper.WriteLog($"省份：{dr["name"]}开始===");

                        try
                        {
                            LogHelper.WriteLog($"省份：{dr["name"]} 清除FanjiaHotel为空数据开始===");

                            var str = $"delete from [fanjiahotelplatform].[dbo].[HotelBestPrices_{dr["code"]}] where hotelid='00000000-0000-0000-0000-000000000000'";
                            var rc = DbHelperSQL.ExecuteSqlByTime(str, 600);

                            LogHelper.WriteLog($"省份：{dr["name"]} 清除FanjiaHotel为空结束，共{rc}条。");
                        }
                        catch (Exception e)
                        {
                            LogHelper.WriteLog($"省份：{dr["name"]}清除FanjiaHotel为空数据错误", e);
                        }

                        try
                        {
                            LogHelper.WriteLog($"省份：{dr["name"]} 清除不相关城市数据开始===");

                            var str = $"delete FROM [fanjiahotelplatform].[dbo].[HotelBestPrices_{dr["code"]}] where citycode not in(select Code from Cities where [ProvinceId] = '{dr["id"]}')";
                            var rc = DbHelperSQL.ExecuteSqlByTime(str, 600);

                            LogHelper.WriteLog($"省份：{dr["name"]} 清除不相关城市数据结束，共{rc}条。");

                        }
                        catch (Exception e)
                        {
                            LogHelper.WriteLog($"省份：{dr["name"]}清除不相关城市数据错误", e);
                        }

                        try
                        {
                            LogHelper.WriteLog($"省份：{dr["name"]} 清除重复数据开始===");

                            var str = $@"WITH lowdata_temp 
                            AS
                            (SELECT u.id, U.[HotelId], U.[EffectiveDate], ROW_NUMBER() OVER(PARTITION BY U.[HotelId], U.[EffectiveDate] ORDER BY U.id) AS DuplicateCount
                            FROM[fanjiahotelplatform].[dbo].[HotelBestPrices_{dr["code"]}] U)
                            DELETE FROM lowdata_temp WHERE DuplicateCount <> 1";
                            var rc = DbHelperSQL.ExecuteSqlByTime(str, 600);

                            LogHelper.WriteLog($"省份：{dr["name"]} 清除重复结束，共{rc}条。");
                        }
                        catch (Exception e)
                        {
                            LogHelper.WriteLog($"省份：{dr["name"]}清除重复数据错误", e);
                        }

                        LogHelper.WriteLog($"省份：{dr["name"]}结束===");
                    }
                }

                MessageBox.Show("数据清除完成！");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                Tools.WriteInfoToFileNoRw(ex.Message);
            }
        }

        private void DistrictCodeRefresh()
        {
            try
            {
                //DataTable dt = DbHelperSQL.Query("SELECT * FROM [Cities] where id='6557602B-E9C8-46AE-8604-3D9F74D90026' ORDER BY CODE").Tables[0];
                DataTable dt = DbHelperSQL.Query("SELECT * FROM [Cities] ORDER BY CODE").Tables[0];
                if (dt != null && dt.Rows.Count > 0)
                {
                    foreach (DataRow dr in dt.Rows)
                    {
                        LogHelper.WriteLog($"城市：{dr["name"]}开始===");
                        DataTable dtDis = DbHelperSQL.Query($"SELECT * FROM [Districts] where cityid='{dr["Id"]}' ORDER BY CODE").Tables[0];

                        foreach (DataRow drDis in dtDis.Rows)
                        {
                            try
                            {
                                var dName = drDis["name"].ToString();
                                var rCode = GetGaoDeAdCode($"{dr["name"]}{dName}");
                                if (!string.IsNullOrEmpty(rCode))
                                {
                                    DbHelperSQL.ExecuteSql(
                                        $"UPDATE Districts SET NationalStandardCode='{rCode}' WHERE ID='{drDis["Id"]}'");

                                    LogHelper.WriteLog($">>>区县：{drDis["name"]}完成>>>");
                                }
                            }
                            catch (Exception e)
                            {
                                LogHelper.WriteLog(e.Message, e);
                            }
                        }

                        LogHelper.WriteLog($"城市：{dr["name"]}结束==");
                    }
                }

            }
            catch (Exception e)
            {
                LogHelper.WriteLog(e.Message, e);
            }
        }

        private void DistrictDataRefresh()
        {
            try
            {
                //DataTable dt = DbHelperSQL.Query("SELECT * FROM [Cities] where id='6557602B-E9C8-46AE-8604-3D9F74D90026' ORDER BY CODE").Tables[0];
                DataTable dt = DbHelperSQL.Query("SELECT * FROM [Cities] ORDER BY CODE").Tables[0];
                if (dt != null && dt.Rows.Count > 0)
                {
                    foreach (DataRow dr in dt.Rows)
                    {
                        LogHelper.WriteLog($"城市：{dr["name"]}开始===");

                        var sql = $@"INSERT INTO [DistrictsTemp]
                                   ([DisCode]
                                   ,[DisName]
                                   ,[code]
                                   ,[name]
                                   ,[cityid])
                                 SELECT p.[Code] DisCode
                                  ,p.[Name] DisName,
                                  d.code,d.name
	                              ,d.cityid
                              FROM [fanjiahotelplatform].[dbo].[DistrictPolicy] p,[Districts] d
                              where p.Code=d.NationalStandardCode 
                              and FanJiaCityId='{dr["Id"]}' and p.ParentCode<>'0'
                              and d.CityId='{dr["Id"]}'";

                        DbHelperSQL.ExecuteSql(
                            $"DELETE FROM DistrictsTemp WHERE cityid='{dr["Id"]}'");

                        DbHelperSQL.ExecuteSql(sql);

                        LogHelper.WriteLog($"城市：{dr["name"]}结束==");
                    }
                }
            }
            catch (Exception e)
            {
                LogHelper.WriteLog(e.Message, e);
            }
        }

        private void DistrictDataDeal()
        {
            try
            {
                //DataTable dt = DbHelperSQL.Query("SELECT * FROM [Cities] where id='6557602B-E9C8-46AE-8604-3D9F74D90026' ORDER BY CODE").Tables[0];
                DataTable dt = DbHelperSQL.Query("SELECT * FROM [Cities] ORDER BY CODE").Tables[0];
                if (dt != null && dt.Rows.Count > 0)
                {
                    foreach (DataRow dr in dt.Rows)
                    {
                        LogHelper.WriteLog($"城市：{dr["name"]}开始===");

                        try
                        {
                            DataTable dtDis = DbHelperSQL.Query($"SELECT * FROM [Districts] where cityid='{dr["Id"]}' ORDER BY CODE").Tables[0];
                            DataTable dtDisP = DbHelperSQL.Query($"SELECT * FROM [DistrictPolicy] where FanJiaCityId='{dr["Id"]}' and ParentCode<>'0'").Tables[0];

                            foreach (DataRow drDis in dtDis.Rows)
                            {
                                try
                                {
                                    var iSql = @"INSERT INTO [dbo].[DistrictsTemp1]
                                               ([DisCode]
                                               ,[DisName]
                                               ,[code]
                                               ,[name]
                                               ,[cityid]
                                               ,[CityName]
                                               ,[Flag]
                                               ,[DId])
                                         VALUES
                                               ('{0}'
                                               ,'{1}'
                                               ,'{2}'
                                               ,'{3}'
                                               ,'{4}'
                                               ,'{5}'
                                               ,{6}
                                               ,'{7}')";

                                    //if (string.IsNullOrEmpty(drDis["NationalStandardCode"].ToString()))
                                    //{
                                    //    DbHelperSQL.ExecuteSql(string.Format(iSql, "", "", drDis["Code"], drDis["Name"],
                                    //        drDis["CityId"], dr["name"], 0, drDis["Id"]));
                                    //    continue;
                                    //}

                                    var dName = drDis["Name"].ToString();
                                    var dNameRlc = dName.Replace("市", "").Replace("县", "").Replace("区", "").Replace("乡", "");
                                    //var rst = dtDisP.Select($"Code='{drDis["NationalStandardCode"]}' OR Name Like '{dNameRlc}%'");
                                    //foreach (DataRow rDr in dtDisP.Rows)
                                    //{
                                    //    var c = rDr["Code"].ToString();
                                    //    var n = drDis["NationalStandardCode"].ToString();
                                    //    var nName = rDr["Name"].ToString();

                                    //    if (!string.IsNullOrEmpty(n) && c == n &&
                                    //        dName.Substring(0, 1) == nName.Substring(0, 1))
                                    //    {
                                    //        DbHelperSQL.ExecuteSql(string.Format(iSql, rDr["Code"], rDr["Name"],
                                    //            drDis["Code"], drDis["Name"],
                                    //            drDis["CityId"], dr["name"], 1, drDis["Id"]));
                                    //        break;
                                    //    }

                                    //    if (c != n &&
                                    //        dName.Substring(0, 2) == nName.Substring(0, 2))
                                    //    {
                                    //        DbHelperSQL.ExecuteSql(string.Format(iSql, rDr["Code"], rDr["Name"], drDis["Code"], drDis["Name"],
                                    //            drDis["CityId"], dr["name"], 1, drDis["Id"]));
                                    //        break;
                                    //    }
                                    //}

                                    foreach (DataRow rDr in dtDisP.Rows)
                                    {
                                        var nName = rDr["Name"].ToString();

                                        if (dName.Substring(0, 2) == nName.Substring(0, 2))
                                        {
                                            DbHelperSQL.ExecuteSql(string.Format(iSql, rDr["Code"], rDr["Name"], drDis["Code"], drDis["Name"],
                                                drDis["CityId"], dr["name"], 1, drDis["Id"]));
                                            break;
                                        }
                                    }


                                    LogHelper.WriteLog($">>>区县：{drDis["name"]}完成>>>");
                                }
                                catch (Exception e)
                                {
                                    LogHelper.WriteLog(e.Message, e);
                                }
                            }

                        }
                        catch (Exception e)
                        {
                            LogHelper.WriteLog(e.Message, e);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                LogHelper.WriteLog(e.Message, e);
            }
        }

        private void DistrictDataDeal1()
        {
            try
            {
                //DataTable dt = DbHelperSQL.Query("SELECT * FROM [Cities] where id='6557602B-E9C8-46AE-8604-3D9F74D90026' ORDER BY CODE").Tables[0];
                DataTable dt = DbHelperSQL.Query("SELECT * FROM [Cities] ORDER BY CODE").Tables[0];
                if (dt != null && dt.Rows.Count > 0)
                {
                    foreach (DataRow dr in dt.Rows)
                    {
                        LogHelper.WriteLog($"城市：{dr["name"]}开始===");

                        try
                        {
                            DataTable dtDis = DbHelperSQL.Query($"SELECT * FROM [Districts] where cityid='{dr["Id"]}' ORDER BY CODE").Tables[0];
                            DataTable dtDisP = DbHelperSQL.Query($"SELECT * FROM [DistrictPolicy] where FanJiaCityId='{dr["Id"]}' and ParentCode<>'0'").Tables[0];

                            foreach (DataRow drDis in dtDis.Rows)
                            {
                                try
                                {
                                    var iSql = @"INSERT INTO [dbo].[DistrictsTemp1]
                                               ([DisCode]
                                               ,[DisName]
                                               ,[code]
                                               ,[name]
                                               ,[cityid]
                                               ,[CityName]
                                               ,[Flag]
                                               ,[DId])
                                         VALUES
                                               ('{0}'
                                               ,'{1}'
                                               ,'{2}'
                                               ,'{3}'
                                               ,'{4}'
                                               ,'{5}'
                                               ,{6}
                                               ,'{7}')";

                                    if (string.IsNullOrEmpty(drDis["NationalStandardCode"].ToString()))
                                    {
                                        DbHelperSQL.ExecuteSql(string.Format(iSql, "", "", drDis["Code"], drDis["Name"],
                                            drDis["CityId"], dr["name"], 0, drDis["Id"]));
                                        continue;
                                    }

                                    var dName = drDis["Name"].ToString();
                                    var dNameRlc = dName.Replace("市", "").Replace("县", "").Replace("区", "").Replace("乡", "");
                                    var rst = dtDisP.Select($"Code='{drDis["NationalStandardCode"]}' OR Name Like '{dNameRlc}%'");
                                    foreach (DataRow rDr in rst)
                                    {
                                        var c = rDr["Code"].ToString();
                                        var n = drDis["NationalStandardCode"].ToString();
                                        var nName = rDr["Name"].ToString();

                                        if (c == n &&
                                            dName.Substring(0, 1) == nName.Substring(0, 1))
                                        {
                                            DbHelperSQL.ExecuteSql(string.Format(iSql, rDr["Code"], rDr["Name"], drDis["Code"], drDis["Name"],
                                                drDis["CityId"], dr["name"], 1, drDis["Id"]));
                                            break;
                                        }
                                    }

                                    LogHelper.WriteLog($">>>区县：{drDis["name"]}完成>>>");
                                }
                                catch (Exception e)
                                {
                                    LogHelper.WriteLog(e.Message, e);
                                }
                            }

                        }
                        catch (Exception e)
                        {
                            LogHelper.WriteLog(e.Message, e);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                LogHelper.WriteLog(e.Message, e);
            }
        }

        /// <summary>
        /// 根据地址获取高德区域编码
        /// </summary>
        /// <param name="address"></param>
        /// <returns></returns>
        private string GetGaoDeAdCode(string address)
        {
            var gaodeResult = RequestGaoDeApiSingle(); //调用高德地图接口获取区域code
            if (gaodeResult is null) return "";
            else
            {
                try
                {
                    var geoModel = GeoModel.FromJson(gaodeResult);
                    if (geoModel.Geocodes.Length == 0)
                    {
                        LogHelper.WriteLog($"【{address}】未刷到数据");
                        return "";
                    }
                    return geoModel.Geocodes[0].Adcode.ToString();
                }
                catch (Exception ex)
                {
                    LogHelper.WriteLog($"【{address}】区域编码获取出错：{ex.Message}");
                    return "";
                }
            }
            string RequestGaoDeApiSingle()
            {
                string apiUrl = "http://restapi.amap.com/v3/geocode/geo";
                string apiKey = "8bc8d2dd7ee8ca44d0ee055b27ff34f4";//"560fa087445311bd9b55beb3202c7533"; 
                string output = "json";

                IDictionary<string, string> param = new Dictionary<string, string>();
                param.Add("key", apiKey);
                param.Add("output", output);

                if (!string.IsNullOrEmpty(address))
                    param.Add("address", address);
                string result = string.Empty;
                try
                {
                    //以 Get 形式请求 Api 地址
                    result = HttpUtils.DoGet(apiUrl, param);
                }
                catch (Exception ex)
                {
                    LogHelper.WriteLog($"===***********{address}获取出错：{ex.Message}");
                    result = null;
                }
                return result;
            }
        }

        private void HotelMergeTest(string cityName, List<Guid> extList)
        {
            try
            {
                var str = $"SELECT id_x,id_y FROM [hotel_merge] where cityname='{cityName}'";
                var dsQuery = DbHelperSQL.Query(str);

                var dic = new Dictionary<Guid, Guid>();

                if (dsQuery.Tables[0].Rows.Count > 0)
                {
                    foreach (DataRow dr in dsQuery.Tables[0].Rows)
                    {
                        var xGuid = Guid.Parse(dr["id_x"].ToString());
                        var yGuid = Guid.Parse(dr["id_y"].ToString());

                        if (extList.Contains(xGuid) || extList.Contains(yGuid))
                            continue;

                        var isCx = dic.ContainsKey(xGuid);
                        var isCy = dic.ContainsKey(yGuid);

                        if (!isCx && !isCy)
                        {
                            var groupId = Guid.NewGuid();
                            dic.Add(xGuid, groupId);
                            dic.Add(yGuid, groupId);
                        }
                        else if (isCx && !isCy)
                        {
                            dic.Add(yGuid, dic[xGuid]);
                        }
                        else if (!isCx && isCy)
                        {
                            dic.Add(xGuid, dic[yGuid]);
                        }
                    }
                }

                if (dic.Count > 0)
                {
                    var timeNow = DateTime.Now;

                    var sDt = new DataTable();
                    sDt.Columns.Add(new DataColumn("HotelId", typeof(Guid)));
                    sDt.Columns.Add(new DataColumn("GroupId", typeof(Guid)));
                    sDt.Columns.Add(new DataColumn("CreationTime", typeof(DateTime)));

                    foreach (var item in dic)
                    {
                        var dr = sDt.NewRow();
                        dr["HotelId"] = item.Key;
                        dr["GroupId"] = item.Value;
                        dr["CreationTime"] = timeNow;

                        sDt.Rows.Add(dr);
                    }

                    //var gList = sDt.AsEnumerable().GroupBy(m => m.Field<Guid>("GroupId"))
                    //    .Select(g => new {g.Key}).ToList();

                    //return;

                    DbHelperSQL.ExecuteSql("TRUNCATE TABLE HotelMergeGroup");

                    var s = DbHelperSQL.SaveListDataBatM(sDt, "HotelMergeGroup");

                    //if (s)
                    //{
                    //    MessageBox.Show("OK!");
                    //}
                    //else
                    //{
                    //    MessageBox.Show("ERROR!");
                    //}

                }
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
                LogHelper.logError.Error(e);
            }
        }

        private void HotelMergeDeal(string cityName, DataTable dtFjSelfHotel)
        {
            try
            {
                //var supplierOrderList = new List<(string, string)>()
                //{
                //    ("607B69C3-2DBA-41B5-BCAF-10A014FAF1DD", "畅联-亚朵"),
                //    //("B6C0D180-D96F-4FCB-A8CF-A16DA3DD987F", "畅联-维也纳"),
                //    ("073A26B3-874C-4903-B787-6465EE23789B", "如家"),
                //    ("0C1C1CDC-C831-4ECF-B362-A47F0E1AC529", "锦江-铂涛直连"),
                //    ("D1D0C7F2-DC98-4B64-B36B-F6CD9E7FBB08", "畅联-格林"),
                //    ("CE833C6E-D06F-46A3-B53E-204E91E83AB4", "畅联-君亭"),
                //    ("557C7AB5-5816-4C1F-8AED-339A96177143", "东呈直连"),
                //    ("89E38E71-47D3-4946-92F4-B41E55ECD38F", "华住直连"),
                //    ("118F9754-0B86-47CB-AAC2-FC75220D90A6", "畅联-都市118"),
                //    ("B8E0D4A6-AB99-444C-B1CB-75D1EA062EFC", "美团直连"),
                //    ("798BD348-9911-4DB4-92CA-848BB0064EC0", "千淘科技"),
                //    ("FFF60DB6-9B70-49D5-AF8B-8F2E6D2ED480", "美团直连-专票"),
                //    ("64FE8F51-3EE2-8A27-A88D-C115027E6EF1", "畅联-秋果"),
                //    ("0DA88C30-89CF-4224-9F39-B95ED7A91957", "畅联-银座"),

                //    ("A8375567-B63C-1B9D-F2BC-AA96D2605F53", "丽呈直连"),
                //    ("1D2E9BDC-FBE2-40BE-8AB4-D28CDC811517", "艺龙直连"),
                //    ("CC7F30A4-1674-32C7-FB2F-0E8D368E2126", "道旅"),
                //    ("00000000-0000-0000-0000-000000000000", "自营"),
                //    ("CC7F30A4-1674-32C7-FB2F-0E8D368E2126", "道旅"),
                //    ("55336424-C7DF-4453-B2F5-72AE8FD0D177", "HotelBeds"),
                //    ("606DD41F-6E52-4B28-A50A-543F542BB972", "逍遥行"),
                //    ("9F22052F-DED5-4710-B75C-3F64431E79F8", "龙腾捷旅"),
                //    ("23796b2d-59d5-b855-91d1-d3a5cc626b6c", "票亿直连"),
                //    ("5AD4E234-8619-71A0-B680-A6A07142ACFF", "雅斯特"),

                //    ("A7685C06-629D-454B-98DA-81F4E6DE1433", "携程直连"),
                //    ("61FDCC1D-888B-4A53-98ED-40AC18A156CB", "途牛笛风"),
                //    ("24924AF6-48D4-4B7A-BA81-103DA6084C69", "四海度假"),
                //    ("138E28A8-17AC-47BD-AD2F-4C032CC1F994", "神兽国旅"),

                //    ("8303EB05-EC9C-464B-93BB-5C3F2FA3CCA3", "泰坦云"),
                //};

                var supplierOrderList = SupplierListConst.SupplierOrderList;

                var strSql = @"SELECT [HotelId]
                            ,[GroupId]
                            , b.SupplierId
                        FROM [HotelMergeGroup] g 
                            left join [dbo].[HotelBasicInfoes] b on g.HotelId = b.id";

                var dt = DbHelperSQL.Query(strSql);

                if (dt?.Tables[0] != null && dt.Tables[0].Rows.Count > 0)
                {
                    //按分组组合出待合并酒店
                    Dictionary<Guid, List<HotelItem>> dic = new Dictionary<Guid, List<HotelItem>>();

                    foreach (DataRow dr in dt.Tables[0].Rows)
                    {
                        var groupId = Guid.Parse(dr["GroupId"].ToString());

                        Guid.TryParse(dr["SupplierId"].ToString(), out var supplierId);

                        if (dic.ContainsKey(groupId))
                        {
                            var list = dic[groupId];
                            list.Add(new HotelItem
                            {
                                HotelId = Guid.Parse(dr["HotelId"].ToString()),
                                SupplierId = supplierId
                            });
                        }
                        else
                        {
                            dic.Add(groupId, new List<HotelItem>()
                            {
                                new HotelItem
                                {
                                    HotelId = Guid.Parse(dr["HotelId"].ToString()),
                                    SupplierId = supplierId
                                }
                            });
                        }
                    }

                    //查询mapping表多供应商映射
                    var mappingDt = DbHelperSQL
                        .Query("select * from HotelMappings where HotelId in(select hotelid from [HotelMergeGroup])")
                        .Tables[0];

                    if (mappingDt.Rows.Count > 0)
                    {
                        var mappingDic = mappingDt.AsEnumerable().GroupBy(h => Guid.Parse(h["HotelId"].ToString()))
                            .ToDictionary(h => h.Key, h => h.ToList());

                        var mappingSaveDt = mappingDt.Clone(); //整理好的映射，将替换成正式数据
                        var mappingRptDt = mappingDt.Clone(); //重复合并的映射，保存后备查

                        var delHotelDt = new DataTable();
                        delHotelDt.Columns.Add(new DataColumn("HotelId", typeof(Guid)));
                        delHotelDt.Columns.Add(new DataColumn("MtHotelId", typeof(Guid)));

                        foreach (var item in dic)
                        {
                            var hList = item.Value;
                            var supplierTmp = new List<Guid>();

                            //判断使用哪个酒店留底合并
                            var hotelId = Guid.Empty;

                            //如果设置过泛嘉自营价格的酒店，则以泛嘉自营酒店为底，不能将泛嘉自营酒店合并到其他酒店
                            if (dtFjSelfHotel != null && dtFjSelfHotel.Rows.Count > 0)
                            {
                                foreach (var h in hList)
                                {
                                    var fjHotelRw = dtFjSelfHotel.Select($"HotelId='{h.HotelId.ToString().ToLower()}'");
                                    if (fjHotelRw?.Length > 0) //设置过泛嘉自营价格的酒店，以该Id的酒店为底
                                    {
                                        hotelId = h.HotelId;
                                        break;
                                    }
                                }
                            }

                            if (hotelId == Guid.Empty)
                            {
                                foreach (var i in supplierOrderList)
                                {
                                    var h = hList.FirstOrDefault(m => m.SupplierId == Guid.Parse(i.Item1));
                                    if (h != null)
                                    {
                                        hotelId = h.HotelId;
                                        break;
                                    }
                                }
                            }

                            //整理多供应商Mapping映射记录
                            foreach (var hotelItem in hList)
                            {
                                if (mappingDic.ContainsKey(hotelItem.HotelId))
                                {
                                    var mappingList = mappingDic[hotelItem.HotelId];

                                    if (hotelItem.HotelId == hotelId)
                                    {
                                        mappingList.ForEach(m =>
                                        {
                                            var mpSupplierId = Guid.Parse(m["SupplierId"].ToString());
                                            if (supplierTmp.Contains(mpSupplierId))
                                            {
                                                mappingRptDt.Rows.Add(m.ItemArray);
                                            }
                                            else
                                            {
                                                supplierTmp.Add(mpSupplierId);
                                                mappingSaveDt.Rows.Add(m.ItemArray);
                                            }
                                        });
                                    }
                                    else
                                    {
                                        foreach (var mp in mappingList)
                                        {
                                            var mpSupplierId = Guid.Parse(mp["SupplierId"].ToString());
                                            if (supplierTmp.Contains(mpSupplierId))
                                            {
                                                mappingRptDt.Rows.Add(mp.ItemArray);
                                            }
                                            else
                                            {
                                                mp["HotelId"] = hotelId;
                                                supplierTmp.Add(mpSupplierId);

                                                mappingSaveDt.Rows.Add(mp.ItemArray);
                                            }
                                        }

                                        var drN = delHotelDt.NewRow();
                                        drN["HotelId"] = hotelItem.HotelId;
                                        drN["MtHotelId"] = hotelId;
                                        delHotelDt.Rows.Add(drN);
                                    }
                                }
                                else
                                {
                                    if (hotelItem.HotelId != hotelId)
                                    {
                                        var drN = delHotelDt.NewRow();
                                        drN["HotelId"] = hotelItem.HotelId;
                                        drN["MtHotelId"] = hotelId;
                                        delHotelDt.Rows.Add(drN);
                                    }
                                }
                            }
                        }

                        //保存处理结果
                        if (mappingSaveDt.Rows.Count > 0)
                        {
                            DbHelperSQL.ExecuteSql("TRUNCATE TABLE HotelMappingMerge");
                            DbHelperSQL.SaveListDataBat(mappingSaveDt, "HotelMappingMerge");

                            LogHelper.WriteLog($"{cityName}-保存处理结果，共{mappingSaveDt.Rows.Count}");
                        }

                        if (mappingRptDt.Rows.Count > 0)
                        {
                            //DbHelperSQL.ExecuteSql("TRUNCATE TABLE HotelMappingMergeRpt");
                            DbHelperSQL.SaveListDataBat(mappingRptDt, "HotelMappingMergeRpt");
                            LogHelper.WriteLog($"{cityName}-mappingRptDt，共{mappingRptDt.Rows.Count}");
                        }

                        if (delHotelDt.Rows.Count > 0)
                        {
                            DbHelperSQL.ExecuteSql("TRUNCATE TABLE HotelMappingMergeDel");
                            DbHelperSQL.SaveListDataBat(delHotelDt, "HotelMappingMergeDel");
                            LogHelper.WriteLog($"{cityName}-需逻辑删除合并掉的酒店，共{delHotelDt.Rows.Count}");
                        }

                        //return;

                        var sqlList = new List<string>();
                        //删除待处理的映射数据
                        sqlList.Add("DELETE FROM HotelMappings WHERE HotelId in(SELECT hotelid FROM [HotelMergeGroup])");

                        //插入整理后替换的映射结果
                        sqlList.Add(@"INSERT INTO [dbo].[HotelMappings]
                                       ([Id]
                                       ,[HotelId]
                                       ,[SupplierId]
                                       ,[SupplierHotelId]
                                       ,[IsActive]
                                       ,[CreationUserId]
                                       ,[CreationUserName]
                                       ,[CreationTime]
                                       ,[LastModificationUserId]
                                       ,[LastModificationUserName]
                                       ,[LastModificationTime]
                                       ,[IsDeleted]
                                       ,[DeleterUserId]
                                       ,[DeleterUserName]
                                       ,[DeletionTime]
                                       ,[Status]
                                       ,[IsOnline]
                                       ,[IsManual])
                                 SELECT
                                       [Id]
                                       ,[HotelId]
                                       ,[SupplierId]
                                       ,[SupplierHotelId]
                                       ,[IsActive]
                                       ,[CreationUserId]
                                       ,'SysMerge'
                                       ,GETDATE()
                                       ,[LastModificationUserId]
                                       ,'SysMerge'
                                       ,GETDATE()
                                       ,[IsDeleted]
                                       ,[DeleterUserId]
                                       ,[DeleterUserName]
                                       ,[DeletionTime]
                                       ,[Status]
                                       ,[IsOnline]
                                       ,[IsManual]
		                               FROM HotelMappingMerge");

                        //逻辑删除被合并掉的酒店
                        sqlList.Add("UPDATE [HotelBasicInfoes] SET IsDeleted=1,DeletionTime=GETDATE(),DeleterUserName='SysMerge',LastModificationTime=GETDATE() WHERE ID IN(SELECT HOTELID FROM HotelMappingMergeDel)");

                        DbHelperSQL.ExecuteSqlTran(sqlList);
                    }
                }

                //MessageBox.Show("完成!");
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
                LogHelper.logError.Error(e);
            }
        }

        private void HotelMergeAllCity()
        {
            try
            {
                var extList = new List<Guid>();
                extList.Add(Guid.Parse("087643B1-5E80-4F3E-8F2A-ACB5AE733D91"));
                extList.Add(Guid.Parse("F44F149D-217E-4957-84F4-6E1C4F034A90"));

                var fjSelfHotelDt = DbHelperMySQL.Query("SELECT hotelid,citycode FROM fjhotelbaseinfo.hotellists")
                    .Tables[0];

                //var str = "SELECT id_x,id_y FROM [dbo].[hotel_merge]";
                //var str = "SELECT distinct cityname FROM [dbo].[hotel_merge] where cityname='杭州'";
                //('杭州','上海','重庆','广州','深圳','成都','北京','宁波','合肥','南京')
                //var str = "SELECT distinct cityname FROM [dbo].[hotel_merge] where cityname in('上海','重庆','广州','深圳','成都','北京','宁波','合肥','南京')";
                var str = "SELECT distinct cityname FROM [dbo].[hotel_merge]";
                var cityDt = DbHelperSQL.Query(str).Tables[0];

                var allCity = DbHelperSQL.Query("SELECT * FROM [Cities]").Tables[0];

                if (cityDt != null && cityDt.Rows.Count > 0)
                {
                    foreach (DataRow dr in cityDt.Rows)
                    {
                        var cityName = dr["cityname"].ToString();
                        var cityCodeDr = allCity.Select($"name='{cityName}'");
                        var cityCode = (cityCodeDr != null && cityCodeDr.Length > 0)
                            ? cityCodeDr[0]["code"].ToString()
                            : "";

                        //if (cityName == "杭州")
                        //    continue;

                        LogHelper.WriteLog($"开始处理{cityName}========");

                        HotelMergeTest(cityName, extList);

                        var citySelfHotelRows = fjSelfHotelDt.Select($"citycode='{cityCode}'");

                        var citySelfHotelDt = new DataTable();
                        if (citySelfHotelRows?.Length>0)
                            citySelfHotelDt = citySelfHotelRows.CopyToDataTable();

                        HotelMergeDeal(cityName, citySelfHotelDt);

                        LogHelper.WriteLog($"======={dr["cityname"]}完成。");
                    }
                }

                MessageBox.Show("OK!");
            }
            catch (Exception e)
            {
                LogHelper.logError.Error(e.Message, e);
            }
        }

        private void HotelMergeSupplier()
        {
            try
            {
                var fjSelfHotelDt = DbHelperMySQL.Query("SELECT hotelid,citycode FROM fjhotelbaseinfo.hotellists")
                    .Tables[0];

                HotelMergeDeal("华住", fjSelfHotelDt);

                MessageBox.Show("OK!");
            }
            catch (Exception e)
            {
                LogHelper.logError.Error(e.Message, e);
            }
        }


        private void button2_Click(object sender, EventArgs e)
        {
            var d = 20000.21M;
            //d = Math.Floor(960M * 9.1888M);

            MessageBox.Show(d.ToString());

            var t = $"{d:0}";//var t = $"{d:N0}";
            //ParseWjsJson();
            MessageBox.Show(t);

            return;
             //var lst = new List<string>() {"aaa", "bbb", "ccc"};

             //foreach (var l in lst)
             //{
             //    if (l == "bbb")
             //        return;
             //}

             //CityMapping();
             //return;

             var txt = this.textBox1.Text;

            //var des = DES.Encode(txt, "FJ*13@~!");
            var des = DES.Decode(txt, "Fanjia@HotelManager.2017");

            MessageBox.Show(des);

            return;

            var s = "8657186777617"; //"0086-0510-81695999";// "0539-7575555-0";

            MessageBox.Show(s.Substring(s.Length - 11));
            //MessageBox.Show(s.Length.ToString());
            //MessageBox.Show(s.IndexOf("0086-", StringComparison.Ordinal).ToString());

            //MessageBox.Show(s.Substring(0, s.LastIndexOf('-')));

            return;

            //var list = new List<string>();

            //for (int i = 0; i < 10; i++)
            //{
            //    list.Add(i.ToString());
            //}

            //var l = list.Skip(9).Take(5);

            //SqlCmd();
            //return;

            //var path = @"C:\Users\Administrator\Desktop\download\HotelSummary.csv";

            //var dt = CsvHelper.ReadCSV(path);

            //var cc = dt.Rows.Count.ToString();
            //MessageBox.Show(cc);

            //var stocks = "10+";
            //stocks = Regex.Replace(stocks, @"[^0-9]", "");
            //var b = Convert.ToInt32(stocks);

            //MessageBox.Show(b.ToString());

            //string DEKEY = "Fanjia@HotelManager.2017";
            //var deStr = this.textBox1.Text;
            //var datastr = AES.Decode(deStr, DEKEY);

            //MessageBox.Show(datastr);
            //var deal = new HotelData();
            //deal.ImportJsonData();
            //deal.ExportToJson();

            //var timeOutTask = Task.Delay(150);//1.设定一个超时的任务
            //var doing = Doing(300);//2. 真正需要执行的任务
            //var task = await Task.WhenAny(doing, timeOutTask);//返回任何一个完成的任务
            //if (task == timeOutTask)//如果超时任务先完成了  就返回  很可惜 他没有完成！
            //{
            //    return "很可惜 他没有完成！";
            //}

            DateTime dt = DateTime.Parse("2021-09-01 10:00");
            if (DateTime.Now > dt)
            {
                MessageBox.Show("11");
            }
        }

        private void ParseWjsJson()
        {
            var listHotel = new List<WjsHotelEntity>();
            // 读取文件并解析
            string[] lines = File.ReadAllLines("D:\\WjsHotelData\\20241023_HotelInfo\\20241023_HotelInfo.json");
            foreach (string line in lines)
            {
                try
                {
                    WjsHotelEntity entity = JsonConvert.DeserializeObject<WjsHotelEntity>(line);
                    // 在这里处理解析后的实体对象
                    Console.WriteLine($"Successfully parsed: {entity}");

                    listHotel.Add(entity);
                }
                catch (JsonException ex)
                {
                    Console.WriteLine($"Error parsing line: {line}");
                    Console.WriteLine($"Error message: {ex.Message}");
                }
            }

            MessageBox.Show(listHotel.Count.ToString());

            if (listHotel.Count > 0)
            {
                var dt = DbHelperSQL.Query("SELECT * FROM A_WjsHotelNo").Tables[0];

                foreach(var h in listHotel)
                {
                    DataRow dr = dt.NewRow();
                    dr["HotelNo"] = h.HotelCode;
                    dr["CreationTime"] = DateTime.Now;

                    dt.Rows.Add(dr);
                }

                DbHelperSQL.SaveListDataBat(dt, "A_WjsHotelNo");

            }

            MessageBox.Show("Finish");
        }

        /// <summary>
        ///做事 需要 ms秒 才能完成
        /// </summary>
        /// <param name="time"></param>
        /// <returns></returns>
        static async Task<string> Doing(int time, string name = "我")
        {
            Console.WriteLine(name + "来了");
            await Task.Delay(TimeSpan.FromMilliseconds(time));
            return string.Format("这活{1}干了：{0}ms ", time, name);
        }

        private void SqlCmd()
        {
            //string tmpFile = Path.GetTempFileName();

            //string argument = string.Format(@" -S {0} -d {1} -i ""{2}"" -o ""{3}""",
            //    ServerName, DatabaseName, fileName, tmpFile);

            //// append user/password if not use integrated security
            //if (!connection.IsIntegratedSecurity)
            //    argument += string.Format(" -U {0} -P {1}", User, Password);

            //var argument = @" -S 192.168.2.210,1433 -U travledb2 -P Lf@niuBi.2017#Xs -d FanjiaHotelPlatform -i ""D:\\export\\zhejiang.sql"" - s "","" -h-1 -W -o ""D:\\zhejaing.json""";
            var argument= @"-S 139.224.66.166 -U travledb2 -P Lf@niuBi.2017#Xs -d FanjiaHotelPlatform -i ""d:\export\zhejiang.sql"" -s "","" -y0 -o ""d:\export\zhejiang.json""";

            var process = Process.Start("sqlcmd.exe", argument);
            process.StartInfo.UseShellExecute = false;
            process.StartInfo.CreateNoWindow = true;
            process.Start();
            while (true)
            {
                // wait for the process exits. The WaitForExit() method doesn't work
                if (process.HasExited)
                    break;
                Thread.Sleep(500);
            }
            MessageBox.Show("OK!");
        }

        private static void SupplierHotelMergeDeal_Bak()
        {

            //直连酒店关联
            var batId = $"{DateTime.Now.ToString("yyyy-MM-dd")}";
            var supplierId = Guid.Parse("557C7AB5-5816-4C1F-8AED-339A96177143");

            DbHelperSQL.ExecuteSql("TRUNCATE TABLE HotelMergeSupplierGroup");

            //关联关系数据
            var mappingDt = DbHelperSQL.Query("SELECT * FROM [HotelMeger_dossenmapping]").Tables[0];

            //直连供应商已存在映射
            var supplierMap = DbHelperSQL
                .Query(
                    @"SELECT m.HotelId,m.SupplierHotelId,b.Name HotelName FROM [HotelMappings] m,[HotelBasicInfoes] b WHERE m.HotelId=b.Id AND m.SupplierId = '557C7AB5-5816-4C1F-8AED-339A96177143' AND SupplierHotelId IN(SELECT[DossenId] FROM [HotelMeger_dossenmapping])")
                .Tables[0];

            //目标供应商已存在映射
            var toMap = DbHelperSQL.Query(
                @"SELECT m.HotelId,m.SupplierHotelId,b.Name HotelName FROM [HotelMappings] m,[HotelBasicInfoes] b
WHERE m.HotelId=b.Id AND m.SupplierId='A7685C06-629D-454B-98DA-81F4E6DE1433' 
AND SupplierHotelId IN(SELECT [CtripId] FROM [HotelMeger_dossenmapping])").Tables[0];

            var rstDt = new DataTable();
            rstDt.Columns.Add(new DataColumn("HotelId", typeof(Guid)));
            rstDt.Columns.Add(new DataColumn("GroupId", typeof(Guid)));
            rstDt.Columns.Add(new DataColumn("HotelName", typeof(string)));
            rstDt.Columns.Add(new DataColumn("SupplierId", typeof(Guid)));
            rstDt.Columns.Add(new DataColumn("BatId", typeof(string)));

            var oneList = new List<Guid>();

            foreach (DataRow mapDr in mappingDt.Rows)
            {
                try
                {
                    //目标供应商的映射
                    var tMap = supplierMap.Select($"SupplierHotelId='{mapDr["CtripId"]}'");

                    //直连供应商的映射
                    var sMap = supplierMap.Select($"SupplierHotelId='{mapDr["DossenId"]}'");

                    var dic = new Dictionary<Guid, string>();

                    var hasSMap = false;
                    foreach (DataRow dr in sMap)
                    {
                        var hotelId = Guid.Parse(dr["HotelId"].ToString());
                        if (!dic.ContainsKey(hotelId))
                            dic.Add(hotelId, dr["HotelName"].ToString());

                        hasSMap = true;
                    }

                    var hasTmap = false;
                    foreach (DataRow dr in tMap)
                    {
                        var hotelId = Guid.Parse(dr["HotelId"].ToString());
                        if (!dic.ContainsKey(hotelId))
                            dic.Add(hotelId, dr["HotelName"].ToString());

                        hasTmap = true;
                    }

                    var groupId = Guid.NewGuid();
                    if (hasTmap && !hasSMap)
                    {
                        var drN = rstDt.NewRow();
                        drN["HotelId"] = Guid.Empty;
                        drN["HotelName"] = mapDr["DossenId"];
                        drN["GroupId"] = groupId;
                        drN["SupplierId"] = supplierId;
                        drN["BatId"] = batId;
                        rstDt.Rows.Add(drN);
                    }

                    if (dic.Count > 1)
                    {
                        foreach (var d in dic)
                        {
                            var drN = rstDt.NewRow();
                            drN["HotelId"] = d.Key;
                            drN["HotelName"] = d.Value;
                            drN["GroupId"] = groupId;
                            drN["SupplierId"] = supplierId;
                            drN["BatId"] = batId;
                            rstDt.Rows.Add(drN);
                        }
                    }
                    //else if (dic.Count == 1)
                    //{
                    //    //oneList.Add(dic.Keys.First());
                    //    var drN = rstDt.NewRow();
                    //    drN["HotelId"] = dic.Keys.First();
                    //    drN["HotelName"] = dic.Values.First();
                    //    drN["GroupId"] = Guid.Empty;
                    //    drN["SupplierId"] = supplierId;
                    //    drN["BatId"] = batId;
                    //    rstDt.Rows.Add(drN);
                    //}
                }
                catch (Exception exception)
                {
                    Console.WriteLine(exception);
                }
            }

            //保存到临时关联表
            if (rstDt.Rows.Count > 0)
            {
                var s = DbHelperSQL.SaveListDataBat(rstDt, "HotelMergeSupplierGroup");
            }

            MessageBox.Show($"保存成功，共{rstDt.Rows.Count}条记录");
        }

        private void CityMapping()
        {
            var sharedRooms = new Dictionary<string, List<string>>();

            sharedRooms.Add("1",new List<string>(){"aaa","bbb"});
            sharedRooms.Add("2", new List<string>() { "ccc", "ddd" });

            var msg = JsonConvert.SerializeObject(sharedRooms);
            Console.Write(msg);

            MessageBox.Show(msg);

            return;

            var dt = DbHelperMySQL.Query("SELECT * FROM hotelbedscity", "MysqlConn").Tables[0];
            var dtNew = DbHelperMySQL.Query("SELECT * FROM hotelbedscity_n where 1=0", "MysqlConn").Tables[0];
            dtNew.TableName = "hotelbedscity_n";

            if (dt != null && dt.Rows.Count > 0)
            {
                foreach (DataRow dr in dt.Rows)
                {
                    var name = dr["Name"].ToString();

                    DataRow drNew = dtNew.NewRow();
                    drNew["code"] = dr["code"];
                    drNew["name"] = dr["name"];

                    if (name.Contains("-"))
                    {
                        var ss = name.Split('-');
                        drNew["NameShort"] = ss[0].Trim();
                        drNew["ProvName"] = ss[1].Trim();
                    }
                    else
                    {
                        drNew["NameShort"] = dr["name"];
                    }

                    dtNew.Rows.Add(drNew);
                }

                DbHelperMySQL.ExecuteSqlWithConn("truncate table hotelbedscity_n", "MysqlConn");

                Stopwatch sw = new Stopwatch();
                using (DbConnection connection = new MySqlConnection(DbHelperMySQL.GetConnStr("MysqlConn")))
                {
                    connection.Open();
                    sw.Start();
                    var bulk = new BulkOperation(connection);
                    bulk.AutoMapKeyName = "Id";
                    bulk.BulkInsert(dtNew);
                    //bulk.BulkUpdate(dt);
                    //bulk.BulkDelete(dt);
                    //bulk.BulkMerge(dt);
                    //bulk.BulkSaveChanges(ds);
                    //bulk.BulkSynchronize(dt);
                    sw.Stop();
                    Console.WriteLine("用时：" + sw.ElapsedMilliseconds.ToString());
                    Console.Read();
                }
            }


            MessageBox.Show("OK!");
        }

        private void button3_Click(object sender, EventArgs e)
        {
            DialogResult result = MessageBox.Show("确定要进行处理吗？", "警告",
                MessageBoxButtons.YesNo, MessageBoxIcon.Warning);

            if (result == DialogResult.Yes)
            {
                HotelMergeAllCity();
            }
        }

        private void button4_Click(object sender, EventArgs e)
        {
            DialogResult result = MessageBox.Show("供应商酒店直接合并，确定要进行处理吗？", "警告",
                MessageBoxButtons.YesNo, MessageBoxIcon.Warning);

            if (result == DialogResult.Yes)
            {
                HotelMergeSupplier();
            }
        }

        private void button5_Click(object sender, EventArgs e)
        {
            DataTable dt = DbHelperSQL.Query("SELECT Id,OrderId,Project,[BackupField] FROM [HotelOrderEntryMainReports]  where bookingtime>'2025-08-26' and IsDeleted=0 and companyname='苏州奥杰汽车（奥杰工业）技术股份有限公司' ").Tables[0];
            if(dt!=null&&dt.Rows.Count>0)
            {
                var dic = new Dictionary<string, string>();

                var count = 0;

                foreach (DataRow dr in dt.Rows)
                {
                    var orderId = dr["OrderId"].ToString();
                    var backup = dr["BackupField"].ToString();
                    var project = dr["Project"].ToString();
                    if (!string.IsNullOrEmpty(backup) && string.IsNullOrEmpty(project))
                    {
                        try
                        {                            
                            var backFields = JsonConvert.DeserializeObject<List<OrderExtraValueNewDto>>(backup ?? "[]");
                            if (backFields != null)
                            {
                                var pVal = "";
                                var pNameVal = "";
                                var bisTripNo = "";
                                var backCostDepartment = backFields.FirstOrDefault(x => x.FieldId == "ProjectName");
                                if (backCostDepartment != null)
                                {
                                    pVal = backCostDepartment.FieldValue;
                                    if (!string.IsNullOrEmpty(pVal))
                                    {
                                        pVal = $",Project='{pVal}'";
                                        pNameVal = $",ProjectName='{pNameVal}'";
                                    }
                                }
                                var backTopDepartment = backFields.FirstOrDefault(x => x.FieldId == "BisTripNo");
                                if (backTopDepartment != null)
                                {
                                    bisTripNo = backTopDepartment.FieldValue;
                                    if (!string.IsNullOrEmpty(bisTripNo))
                                    {
                                        bisTripNo = $",BisTripNo='{bisTripNo}'";
                                    }
                                }

                                var sql = $"UPDATE [HotelOrderEntryMainReports] SET LastModificationTime=GETDATE(),LastModificationUserName='SysMdf'{pVal}{bisTripNo} WHERE Id='{dr["Id"].ToString()}'";
                                DbHelperSQL.ExecuteSql(sql);

                                if (!dic.ContainsKey(orderId))
                                {
                                    var sqlOrder = $"UPDATE [HotelOrders] SET LastModificationTime=GETDATE(),LastModificationUserName='SysMdf'{pNameVal}{bisTripNo} WHERE Id='{orderId}'";
                                    DbHelperSQL.ExecuteSql(sqlOrder);
                                    dic.Add(orderId, "1");
                                }

                                count++;
                            }                            
                        }
                        catch (Exception ex)
                        {
                            LogHelper.logError.Error(ex.Message, ex);
                        }
                    }
                }

                MessageBox.Show($"处理完成，{count}条");
            }
        }
    }

    /// <summary>
    /// 订单额外信息值保存Dto
    /// </summary>
    public class OrderExtraValueNewDto
    {
        /// <summary>
        /// 字段唯一标识ID
        /// </summary>
        public string FieldId { get; set; }

        /// <summary>
        /// 0：预留字段，1：拓展字段，2：自定义字段
        /// </summary>
        public string FieldSource { get; set; }

        // 私有字段用于存储FieldTitle的值
        private string _fieldTitle;

        /// <summary>
        /// 字段标题，如果是预留字段，则为字段的标题；如果是拓展字段或自定义字段，则为字段的名称
        /// </summary>
        public string FieldTitle
        {
            get
            {
                // 当FieldSource为0时返回FieldId，否则返回私有字段的值
                return FieldSource == "0" ? FieldId : _fieldTitle;
            }
            set
            {
                if (FieldSource == "0")
                {
                    FieldId = value;
                }
                else
                {
                    // 给私有字段赋值，避免递归
                    _fieldTitle = value;
                }
            }
        }

        /// <summary>
        /// 字段列名（冗余字段，方便后期查询）
        /// </summary>
        public string FieldName { get; set; }

        /// <summary>
        /// 字段的值
        /// </summary>
        public string FieldValue { get; set; }
    }

    class HotelItem
    {
        public Guid HotelId { get; set; }
        public Guid SupplierId { get; set; }
    }

    public class HotelImage
    {
        public string ImageUrl { get; set; }
        public string ImageType { get; set; }
    }
    public class HotelFacility
    {
        public string FacilityName { get; set; }
        public string FacilityValue { get; set; }
    }

    public class WjsHotelEntity
    {
        public int RoomNumber { get; set; }
        public string CityCode { get; set; }
        public string RegionName { get; set; }
        public string Latitude { get; set; }
        public string OpeningTime { get; set; }
        public string MainPicture { get; set; }
        public string PhoneNum { get; set; }
        public long UpdateTimeStamp { get; set; }
        public string RegionCode { get; set; }
        public string AddressUs { get; set; }
        public List<HotelImage> HotelImgs { get; set; }
        public List<HotelFacility> HotelFacilities { get; set; }
        public string StarRating { get; set; }
        public string Introduction { get; set; }
        public string Longitude { get; set; }
        public string Address { get; set; }
        public string BusinessZone { get; set; }
        public string FixTime { get; set; }
        public string HotelCode { get; set; }
        public string GovZone { get; set; }
        public string HotelBrand { get; set; }
        public string FaxNum { get; set; }
        public string NameUs { get; set; }
        public string Name { get; set; }
        public string Facilities { get; set; }
        public string Status { get; set; }
    }


}
